package com.googlecode.mailnet.emf.netmodel.ui;


import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;

import com.googlecode.mailnet.emf.netmodel.NetworkConfigurationModel;
import com.googlecode.mailnet.emf.netmodel.diagram.edit.parts.NetworkConfigurationModelEditPart;
import com.googlecode.mailnet.emf.netmodel.diagram.part.NetmodelDiagramEditor;
import com.googlecode.mailnet.emf.netmodel.impl.NetworkConfigurationModelImpl;
import com.googlecode.mailnet.emf.netmodel.simulation.DecorationUtils;
import com.googlecode.mailnet.emf.netmodel.simulation.ISimulationListener;
import com.googlecode.mailnet.emf.netmodel.simulation.SimulationContext;

public class SimulationView extends ViewPart implements ISimulationListener, ISelectionListener {

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object first = ((IStructuredSelection) selection).getFirstElement();
			if (first instanceof NetworkConfigurationModelEditPart) {
				NetworkConfigurationModelEditPart editPart = (NetworkConfigurationModelEditPart) first;
				model = (NetworkConfigurationModel) editPart.resolveSemanticElement();
				onModelChanged(model);
			}
		}
	}

	@Override
	public void onChanged(final SimulationContext context) {
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				if (context != null) {
					statusLabel.setText("Current step: " + context.getInfo().now());
					statusLabel.pack();
				}
			}
		});
	}

	/**
	 * The constructor.
	 */
	public SimulationView() {}

	NetworkConfigurationModel model = null;
	
	Label statusLabel;
	Combo decoratorCombo;
	
	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		getViewSite().getPage().addSelectionListener(this);
		parent.setLayout(new GridLayout(1, false));
		statusLabel = new Label(parent, SWT.NONE);
		statusLabel.setText("Simulation not launched for this diagram. Press \"Run\" to start.");
		Label comboLabel = new Label(parent, SWT.NONE);
		comboLabel.setText("Choose visualization algorithm:");
		decoratorCombo = new Combo(parent, SWT.READ_ONLY | SWT.DROP_DOWN);
		decoratorCombo.add(DecorationUtils.DECORATOR_FAILURES);
		decoratorCombo.add(DecorationUtils.DECORATOR_FAILURE_PROBABILITY);
		// decoratorCombo.add(DecorationUtils.DECORATOR_IMPORTANCE_PER_STEP);
		decoratorCombo.add(DecorationUtils.DECORATOR_AVERAGE_IMPORTANCE);
		decoratorCombo.add(DecorationUtils.DECORATOR_BOTTLE_NECK);
		decoratorCombo.add(DecorationUtils.DECORATOR_HIGH_RISK);
		decoratorCombo.select(0);
		decoratorCombo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				super.widgetSelected(e);
				String selectedItem = decoratorCombo.getItem(decoratorCombo.getSelectionIndex());
				if (model != null) {
					((NetworkConfigurationModelImpl) model).setDecoratorId(selectedItem);
					IEditorPart editorPart = getSite().getPage().getActiveEditor();
					if (!(editorPart instanceof NetmodelDiagramEditor)) return;
					NetmodelDiagramEditor editor = (NetmodelDiagramEditor) editorPart;
					DiagramEditPart diagramEditPart = editor.getDiagramEditPart();
					NetworkConfigurationModelEditPart modelEditPart = (NetworkConfigurationModelEditPart) diagramEditPart;
					modelEditPart.onDecoratorUpdated();
				}
			}
		});
//		hookGlobalActions();
//		makeActions();
//		hookContextMenu();
//		hookDoubleClickAction();
//		contributeToActionBars();
		getSite().getPage().addSelectionListener(this);
	}

//	private void hookContextMenu() {
//		MenuManager menuMgr = new MenuManager("#PopupMenu");
//		menuMgr.setRemoveAllWhenShown(true);
//		menuMgr.addMenuListener(new IMenuListener() {
//			public void menuAboutToShow(IMenuManager manager) {
//				SimulationView.this.fillContextMenu(manager);
//			}
//		});
//		Menu menu = menuMgr.createContextMenu(viewer.getControl());
//		viewer.getControl().setMenu(menu);
//		getSite().registerContextMenu(menuMgr, viewer);
//	}

//	private void contributeToActionBars() {
//		IActionBars bars = getViewSite().getActionBars();
//		fillLocalPullDown(bars.getMenuManager());
//		fillLocalToolBar(bars.getToolBarManager());
//	}

//	private void fillLocalPullDown(IMenuManager manager) {
//		manager.add(action1);
//		manager.add(new Separator());
//		manager.add(action2);
//	}

//	private void fillContextMenu(IMenuManager manager) {
//		manager.add(action1);
//		manager.add(action2);
		// Other plug-ins can contribute there actions here
//		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
//	}
	
//	private void fillLocalToolBar(IToolBarManager manager) {
//		manager.add(action1);
//		manager.add(action2);
//	}

//	private void makeActions() {
//		action1 = new Action() {
//			public void run() {
//				showMessage("Action 1 executed");
//			}
//		};
//		action1.setText("Action 1");
//		action1.setToolTipText("Action 1 tooltip");
//		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
//			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
//		
//		action2 = new Action() {
//			public void run() {
//				showMessage("Action 2 executed");
//			}
//		};
//		action2.setText("Accontexttion 2");
//		action2.setToolTipText("Action 2 tooltip");
//		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
//				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
//		doubleClickAction = new Action() {
//			public void run() {
//				ISelection selection = viewer.getSelection();
//				Object obj = ((IStructuredSelection)selection).getFirstElement();
//				showMessage("Double-click detected on "+obj.toString());
//			}
//		};
//	}

//	private void hookDoubleClickAction() {
//		viewer.addDoubleClickListener(new IDoubleClickListener() {
//			public void doubleClick(DoubleClickEvent event) {
//				doubleClickAction.run();
//			}
//		});
//	}
//	private void showMessage(String message) {
//		MessageDialog.openInformation(
//			viewer.getControl().getShell(),
//			"Симуляция",
//			message);
//	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {}
	
	public void onModelChanged(NetworkConfigurationModel model) {
		if (this.model != null && this.model.getSimulationContext() != null) {
			this.model.getSimulationContext().removeListener(this);
		}
		this.model = model;
	
		if (model != null) {
			if (decoratorCombo.getItems() != null) {
				String[] items = decoratorCombo.getItems();
				for (int i = 0; i < items.length; ++i) {
					String id = model.getDecoratorId();
					if  (items[i] == id) {
						decoratorCombo.select(i);
					}
				}
			}
		}
		if (model != null && model.getSimulationContext() != null) {
			model.getSimulationContext().addListener(this);
			// System.out.println("simulation")
			onChanged(model.getSimulationContext());
		} else {
			statusLabel.setText("Simulation not launched for this diagram. Open diagram and press \"Run\" to start.");
		}
		
	}
}